package com.qiyun.dinghuohui.base;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.qiyun.dinghuohui.ApplicationDataHolder;
import com.qiyun.dinghuohui.Login;
import com.qiyun.dinghuohui.MainActivity;
import com.qiyun.dinghuohui.R;
import com.qiyun.dinghuohui.common.ApiName;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.dialog.CustomProgressDialog;
import com.qiyun.dinghuohui.inter.PublicCallBackResult;
import com.qiyun.dinghuohui.utils.AsyncJsonTask;
import com.qiyun.dinghuohui.utils.Constants;
import com.qiyun.dinghuohui.utils.InjectUtil;
import com.qiyun.dinghuohui.utils.JsonBuilder;
import com.qiyun.dinghuohui.utils.ResultListener;
import com.qiyun.dinghuohui.utils.SysUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by xlm on 2018\5\25 0025
 */

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener, ResultListener,
        PublicCallBackResult {
    private static final String TAG = "BaseActivity";
    private Toast mToast;
    private CustomProgressDialog mCustomProgressDialog;
    private ProgressDialog mProgressDialog;
    private FragmentManager mFragmentManager;
    private BaseFragment mCurrentFragment;
    public BaseActivity instance = null;
    public static final int DLG = 0x0100;
    protected ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        onGetIntent(getIntent());
        super.onCreate(savedInstanceState);
        instance = this;
        ApplicationDataHolder.getApp().addActivity(instance);
        if (instance instanceof Login) {
            setTranslucentStatus(Color.parseColor("#666666"));
        } else if (instance instanceof MainActivity) {

        } else {
            initImmersionBar(R.color.colorPrimaryDark);
        }
        onSetContentView();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        injectView();
        initViews();
        afterOnCreate(savedInstanceState);
        onSetListener();
    }

    // 检测是否有数据未同步
    public boolean checkDataNeedSync(ResultListener resultListener,
                                     ApplicationDataHolder adh,
                                     Handler mHandler,
                                     int OP_SYNC_DATA,
                                     boolean reReadLocal,
                                     boolean showToast) {
        String saccount = "";
        if (reReadLocal) {
            CommonDataSets.readLocalUserDataToReset();
        }
        JSONArray notsyncdata_flag = CommonDataSets.getGoodsFlagNotSync();
        JSONArray notsyncdata_order = CommonDataSets.getOrderNotSync(adh.getUsername());
        JSONArray notsyncdata_display = CommonDataSets.getGoodsDisplayFlagNotSync();
        JSONObject orderconfig = CommonDataSets.getOrderShowConfigNotSync();
        JSONArray notsyncdata_configcode = CommonDataSets.getUserConfigCodeNotSync();
        JSONArray notsyncdata_sizegroup = CommonDataSets.getOrderSizeGroupNotSync();
        if (notsyncdata_flag.length() > 0 || notsyncdata_order.length() > 0
                || notsyncdata_display.length() > 0 || orderconfig != null
                || notsyncdata_configcode.length() > 0) {
            // 有数据需要同步先
            // 需要进行同步
            if (showToast) {
                showToast("正在同步数据...");
            }
            mHandler.sendEmptyMessage(Constants.SHOW_LOADING);
            JSONObject postData = null;
            JsonBuilder jb = new JsonBuilder();
            JSONObject json = new JSONObject();
            if (notsyncdata_flag.length() > 0) {
                try {
                    saccount = notsyncdata_flag.getJSONObject(0).getString("account");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                if (notsyncdata_order.length() > 0) {
                    try {
                        saccount = notsyncdata_order.getJSONObject(0).getString("account");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            try {
                json.put("data_flag", notsyncdata_flag);
                json.put("data_order", notsyncdata_order);
                json.put("data_display", notsyncdata_display);
                if (orderconfig != null) {
                    json.put("data_orderconfig", orderconfig);
                }
                json.put("data_configcode", notsyncdata_configcode);
                json.put("data_sizegroup", notsyncdata_sizegroup);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            postData = jb.setUsername(saccount).setOp(OP_SYNC_DATA)
                    .setDeviceId(adh.getDeviceId())
                    .setBattery(adh.getBattery()).setPostData(json).buildJson();
            new AsyncJsonTask(adh.getServerUrl(true, 0, "B"), ApiName.SYNCDATA, resultListener).execute(postData);
            return true;
        }
        return false;
    }

    public void AppDialogShow() {
        try {
            showDialog(Constants.DIALOG_PROGRESS);
        } catch (Exception e) {
        }
    }

    public void AppDialogShow(int id) {
        try {
            showDialog(id);
        } catch (Exception e) {
        }
    }

    public void AppDialogHide() {
        try {
            dismissDialog(Constants.DIALOG_PROGRESS);
        } catch (Exception e) {
        }
    }


    /**
     * activity上下文
     *
     * @return
     */
    public BaseActivity getThis() {
        return instance;
    }

    /**
     * 获取传递的intent
     *
     * @param intent
     */
    protected void onGetIntent(Intent intent) {

    }

    /**
     * 通过注解自动绑定资源ID
     */
    private void injectView() {
        InjectUtil.injectActivityFields(this, false);
    }

    protected abstract void onSetContentView();

    protected abstract void initViews();

    protected abstract void onSetListener();

    protected abstract void afterOnCreate(Bundle savedInstanceState);

    public FragmentManager initFragmentManager(int framlayout) {
        mFragmentManager = new FragmentManager(getThis(), framlayout);
        return mFragmentManager;
    }

    public void setCurrentFragment(BaseFragment fragment) {
        mCurrentFragment = fragment;
    }

    public BaseFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    @Override
    public void onBackPressed() {
        if (mCurrentFragment != null) {
            mCurrentFragment.onBackPressed();
            return;
        }
        afterBackPressed();
    }

    protected void afterBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        beforeFinish();
        super.finish();
    }

    protected void beforeFinish() {

    }

    @Override
    protected void onDestroy() {
        hideSoftInput();
        ApplicationDataHolder.getApp().removeActivity(this);
        super.onDestroy();
    }

    //隐藏软键盘
    public void hideSoftInput() {
        View view = getCurrentFocus();
        if (view != null) {
            SysUtil.hideSoftInput(view);
        }
    }

    /**
     * 设置透明状态栏
     */
    private void setTranslucentStatus(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0 全透明实现
            Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color);
        } else {//4.4 全透明状态栏
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar(int color) {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
//      StatusBarCompat.setStatusBarColor(this, Color.parseColor("#40000000"));
//      StatusBarCompat.setStatusBarColor(this, Color.parseColor("#e46641"));
        mImmersionBar.fitsSystemWindows(true).statusBarColor(color).init();
    }

    /**
     * 事件监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

    }

    /**
     * Toast展示
     *
     * @param msg
     */
    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast != null) {
                    mToast.cancel();
                    mToast = null;
                }
                View layout = getLayoutInflater().inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.rl_toast));
                TextView text = (TextView) layout.findViewById(R.id.toast_content);
                text.setText(msg);
                mToast = new Toast(getThis());
                mToast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 240);
                mToast.setDuration(Toast.LENGTH_SHORT);
                mToast.setView(layout);
                mToast.show();
            }
        });
    }

    /**
     * 展示加载dialog
     *
     * @param msg
     */
    public void showLoading(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mCustomProgressDialog == null) {
                        mCustomProgressDialog = new CustomProgressDialog(getThis());
                    }
                    mCustomProgressDialog.setMessage(msg);
                    mCustomProgressDialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消加载dialog
     */
    public void dismissLoading() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mCustomProgressDialog != null
                            && mCustomProgressDialog.isShowing()) {
                        mCustomProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 下载dialog
     *
     * @param msg
     * @return
     */
    private ProgressDialog getProgressDialog(String msg) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(BaseActivity.this);
        }
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(msg);
        return mProgressDialog;
    }

    /**
     * 下载进度dialog
     *
     * @param msg
     */
    public void showDownProgress(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    getProgressDialog(msg).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 取消下载dialog
     */
    public void dismissDownProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 检查内存卡权限
     *
     * @param request_code
     * @return
     */
    public boolean checkStoragePermission(int request_code) {
        int permissionr = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            permissionr = ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        int permissionw = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionr == PackageManager.PERMISSION_GRANTED
                && permissionw == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = new String[0];
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                PERMISSIONS_STORAGE = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                };
            }
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 摄像头
     *
     * @param request_code
     * @return
     */
    public boolean checkCameraPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.CAMERA);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.CAMERA
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 录音
     *
     * @param request_code
     * @return
     */
    public boolean checkRecordAudioPermission(int request_code) {
        int permission = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.RECORD_AUDIO);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.RECORD_AUDIO
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 地图定位
     *
     * @param request_code
     * @return
     */
    public boolean checkLocationPermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionc = ActivityCompat.checkSelfPermission(getThis(),
                Manifest.permission.ACCESS_COARSE_LOCATION);
        if (permissionf == PackageManager.PERMISSION_GRANTED
                && permissionc == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            ActivityCompat.requestPermissions(getThis(), PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    /**
     * 通讯录权限
     *
     * @param request_code
     * @return
     */
    public boolean checkReadPhoneStatePermission(int request_code) {
        int permissionf = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE);
        if (permissionf == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_PHONE_STATE};
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
                    request_code);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (permissions[0]) {
            case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onStoragePermission(requestCode, true);
                } else {
                    onStoragePermission(requestCode, false);
                }
                break;
            case Manifest.permission.CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onCameraPermission(requestCode, true);
                } else {
                    onCameraPermission(requestCode, false);
                }
                break;
            case Manifest.permission.RECORD_AUDIO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onRecordAudioPermission(requestCode, true);
                } else {
                    onRecordAudioPermission(requestCode, false);
                }
                break;
            case Manifest.permission.ACCESS_FINE_LOCATION:
            case Manifest.permission.ACCESS_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    onLocationPermission(requestCode, true);
                } else {
                    onLocationPermission(requestCode, false);
                }
                break;
            case Manifest.permission.READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onReadPhoneStatePermission(requestCode, true);
                } else {
                    onReadPhoneStatePermission(requestCode, false);
                }
                break;
        }
    }

    public void onStoragePermission(int result_code, boolean result) {

    }

    public void onCameraPermission(int result_code, boolean result) {

    }

    public void onRecordAudioPermission(int result_code, boolean result) {

    }

    public void onLocationPermission(int result_code, boolean result) {

    }

    public void onReadPhoneStatePermission(int result_code, boolean result) {

    }

}
